package com.huluobo.jetpackdemo.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.huluobo.jetpackdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception

class CoroutineActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coroutine)

//        //GlobalScope 全域协程,一般不要用,作用域为当前的application,只有当应用程序销毁的时候,才会跟随销毁
//        val job = GlobalScope.launch(Dispatchers.IO) {
//            Log.i("TagA", "当前线程:${Thread.currentThread()}")
//        }
//
//        job.cancel()
//
//        GlobalScope.launch(Dispatchers.Main) {
//            Log.i("TagA", "当前线程:${Thread.currentThread()}")
//        }


        val job = Job()
        //协程作用域,相比于全域协程,会自身管理生命周期,内存不足或者创建过多时会自动销毁
        CoroutineScope(job).launch {
//            val result = async {
//                try {
//                    delay(5000)
//                    "运行结果:${3 / 0}"
//                } catch (e: Exception) {
//                    "结果异常"
//                }
//            }.await()
//            Log.i("TagA", "result:${result}")

            val startTime = System.currentTimeMillis()
            val result = async {
                delay(5000)
                "操作成功"
            }

            val result2 = async {
                delay(4000)
                "获取成功"
            }

            Log.i("TagA", "执行结果:${result.await()},${result2.await()}")
            val endTime = System.currentTimeMillis()
            Log.i("TagA", "执行时间:${endTime - startTime}")

        }
    }
}